package controllers

import (
	"github.com/astaxie/beego"
	"shorturl/shorturl"
)

type ShortenController struct {
	beego.Controller
}

func (this *ShortenController) Gen() {
	var pair UrlPair
	pair.Desc = s2lDesc
	pair.Long = this.Input().Get(PARAM)
	urlmd5 := shorturl.GetUrlMd5(pair.Long)
	if !urlCache.IsExist(urlmd5) {
		if shortUrlMode == "md5" {
			pair.Short = shorturl.BaseMD5GenerateShortUrl(pair.Long, shortUrlSecurityKey, shorturlSize)
		}
		if shortUrlMode == "base62" {

			pair.Short = shorturl.Base62GenerateShortUrlBase62()
		}
		err := urlCache.Put(urlmd5, pair.Short, expired)
		if err != nil {
			beego.Warning(err)
		}
		err = urlCache.Put(pair.Short, pair.Long, expired)
		if err != nil {
			beego.Warning(err)
		}
	} else {
		pair.Short = urlCache.Get(urlmd5).(string)
	}
	this.Data[RETVAL] = pair
	this.ServeJson()
}
